package com.itheima.web;

import com.itheima.dao.UserMapper;
import com.itheima.pojo.User;
import com.itheima.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Xiao
 * @date 2021/8/30
 */
@WebServlet("/log")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        /*String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();*/
        //使用SqlSessionFactoryUtils工具类
        SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //接收数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = mapper.select(username, password);
        PrintWriter writer = resp.getWriter();
        if (user == null) {
            writer.write("登录失败。。。");
        } else {
            writer.write("登录成功。。。");
        }
        sqlSession.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
